package com.zyk.grate_offer.class09;

/**
 * 给定一个数, 判断是否是某个的步骤和 (123的步骤和 -> 123 + 12 + 1)
 *
 * @author zhangsan
 * @date 2021/5/23 11:19
 */
public class Code01_IsStepSum {

    // a > b 那么 a的步骤和必定 >ｂ的步骤和．　所以这道题来二分
    public static int isStepSum(int stepSum) {
        int l = 1, r = stepSum;
        int m, curSum;
        while (l <= r) {
            m = l + ((r - l) >> 1);
            curSum = stepSum(m);
            if (curSum == stepSum) {
                return m;
            } else if (curSum > stepSum) {    // 大了, 左边
                r = m - 1;
            } else {
                l = m + 1;
            }
        }
        return -1;
    }

    public static int stepSum(int num) {
        int ans = num;
        while (num != 0) {
            ans += (num /= 10);
        }
        return ans;
    }


    public static void main(String[] args) {
        /*for (int i = 0; i < 200; i++) {
            System.out.println(i + " : " + stepSum(i));
        }*/

        int num = 7268;
        System.out.println(isStepSum(num));
    }

}
